package com.yonyou.iuap.jxzy.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;


























import org.apache.commons.lang.WordUtils;

import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.commons.collections.MapUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.base.web.BaseController;
import com.yonyou.iuap.mvc.constants.RequestStatusEnum;
import com.yonyou.iuap.jxzy.entity.DomesticPaper;
import com.yonyou.iuap.jxzy.entity.DomesticPaper_b;
import com.yonyou.iuap.jxzy.entity.PoundPictrueUrlEntity;
import com.yonyou.iuap.jxzy.service.DomesticPaperService;
import com.yonyou.iuap.jxzy.service.DomesticPaper_bService;
import com.yonyou.iuap.mvc.annotation.FrontModelExchange;
import com.yonyou.iuap.mvc.type.SearchParams;
import com.yonyou.iuap.mvc.type.JsonResponse;
import com.yonyou.metadata.mybatis.util.publish.model.data.UFDateTime;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;

import org.springframework.util.StringUtils;
/**
 * 说明：国内废纸称重 基础Controller——提供数据增、删、改、查、导入导出等rest接口
 * 
 * @date 2019-5-29 18:23:40
 */
@Controller
@RequestMapping(value="/jx_domesticPaper")
public class DomesticPaperController extends BaseController{

    private Logger logger = LoggerFactory.getLogger(DomesticPaperController.class);

    private DomesticPaperService domesticPaperService;

    @Autowired
    public void setDomesticPaperService(DomesticPaperService domesticPaperService) {
        this.domesticPaperService = domesticPaperService;
    }
    
    private DomesticPaper_bService domesticPaper_bService;

    @Autowired
    public void setDomesticPaper_bService(DomesticPaper_bService domesticPaper_bService) {
        this.domesticPaper_bService = domesticPaper_bService;
    }


    @RequestMapping(value = "/list", method = {RequestMethod.GET})
    @ResponseBody
    public Object list(PageRequest pageRequest, SearchParams searchParams) {
//    	searchParams.
    	Map<String, Object> searchMap = searchParams.getSearchMap();
    	if(searchMap.get("pk_material")!=null){
    		String string = searchMap.get("pk_material").toString();
    		searchMap.put("pk_material", string.replace(",", "','"));
    	}
    	if(searchMap.get("heapNo")!=null){
    		String string = searchMap.get("heapNo").toString();
    		searchMap.put("heapNo", string.replace(",", "','"));
    	}
        Page<DomesticPaper> page = this.domesticPaperService.selectAllByPage(pageRequest, searchParams);
//    	this.domesticPaperService.selectAllByPage(pageRequest, searchParams)
    	Map<String, Object> map = new HashMap<String, Object>();
    	ArrayList<Object> arrayList = new ArrayList<Object>();
//        map.put("content", page.getContent());
//        arrayList.add(map);
    	map.put("data", page);
        return this.buildMapSuccess(map);
    }
    
    @RequestMapping(value = "/childlist", method = {RequestMethod.GET})
    @ResponseBody
    public Object childlist(PageRequest pageRequest, SearchParams searchParams) {
    	Map<String, Object> searchMap = searchParams.getSearchMap();
//    	Object id = searchMap.get("pk_domesticpaper");
    	Object id = searchMap.get("id");
    	HashMap<String, Object> queryParams = new HashMap<String, Object>();
    	queryParams.put("serialNo", id);
        List<DomesticPaper_b> queryList = this.domesticPaper_bService.queryList(queryParams);
        for (DomesticPaper_b domesticPaper_b : queryList) {
        	String imgUrls = domesticPaper_b.getImgUrls();
//        	JSONArray imgs = new JSONArray();
        	String[] split = (imgUrls==null?new String[0]:imgUrls.split(","));
        	if(split.length==0){
        		continue;
        	}else{
//        		for (String path : split) {
//        			imgs.add(path);
//				}
        		domesticPaper_b.setImgUrl(split);
        	}
//        	domesticPaper_b.setImgUrl(imgs.toJSONString());
		}
    	Map<String, Object> map = new HashMap<String, Object>();
    	ArrayList<Object> arrayList = new ArrayList<Object>();
        map.put("content", queryList);
        arrayList.add(map);
        return this.buildSuccess("data", map);
    }
    

    @RequestMapping(value = "/get")
    @ResponseBody
    public Object get(PageRequest pageRequest, SearchParams searchParams) {
        String id = MapUtils.getString(searchParams.getSearchMap(), "id");
        if (id==null){
            return this.buildSuccess();//前端约定传空id则拿到空对象
        }
        if(StrUtil.isBlank(id)) {
            return this.buildError("msg", "主键id参数为空!", RequestStatusEnum.FAIL_FIELD);
        }else {
            DomesticPaper entity = this.domesticPaperService.findById(id);
            return this.buildSuccess(entity);
        }
    }


    @RequestMapping(value = "/save")
    @ResponseBody
    public Object save(@RequestBody DomesticPaper entity,HttpServletRequest request, HttpServletResponse response) {
    	String userName=null;
    	Cookie[]  cookies=request.getCookies();
		if (cookies!=null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("_A_P_userLoginName")) {
                	userName = cookie.getValue();
                }
            }
		}
        JsonResponse jsonResp;
        try {
        	entity.setModifyuser(userName==null?"~":userName);//设置修改人用户编码
        	entity.setModifytime(new UFDateTime().toString());//设置修改时间
            this.domesticPaperService.saveH(entity);
            jsonResp = this.buildSuccess(entity);
        }catch(Exception exp) {
            jsonResp = this.buildError("msg", exp.getMessage(), RequestStatusEnum.FAIL_FIELD);
        }
        return jsonResp;
    }

    @RequestMapping(value = "/saveBatch")
    @ResponseBody
    public Object saveBatch(@RequestBody List<DomesticPaper> listData) {
        this.domesticPaperService.saveBatch(listData);
        return this.buildSuccess();
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestBody DomesticPaper entity, HttpServletRequest request, HttpServletResponse response) throws Exception {
        this.domesticPaperService.delete(entity);
        return super.buildSuccess();
    }

    @RequestMapping(value = "/deleteBatch")
    @ResponseBody
    public Object deleteBatch(@RequestBody List<DomesticPaper> listData, HttpServletRequest request, HttpServletResponse response) throws Exception {
        this.domesticPaperService.deleteBatch(listData);
        return super.buildSuccess();
    }
    
    @RequestMapping(value = "/verify")
    @ResponseBody
    public Object verify(@RequestBody String json, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	String userName=null;
    	Cookie[]  cookies=request.getCookies();
		if (cookies!=null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("_A_P_userLoginName")) {
                	userName = cookie.getValue();
                }
            }
		}
    	JSONObject parseObject = new JSONObject().parseObject(json);
    	JSONArray jsonArray = parseObject.getJSONArray("param");
    	List<DomesticPaper> listData = jsonArray.toJavaList(DomesticPaper.class);
    	for (DomesticPaper domesticPaper : listData) {
    		domesticPaper.setAuditor(userName==null?"~":userName);//设置修改人用户编码
    		domesticPaper.setAuditortime(new UFDateTime().toString());//设置修改时间
		}
    	this.domesticPaperService.verify(listData,true);
        return super.buildSuccess();
    }

    @RequestMapping(value = "/cancelverify")
    @ResponseBody
    public Object cancelverify(@RequestBody String json, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	JSONObject parseObject = new JSONObject().parseObject(json);
    	JSONArray jsonArray = parseObject.getJSONArray("param");
    	List<DomesticPaper> listData = jsonArray.toJavaList(DomesticPaper.class);
    	for (DomesticPaper domesticPaper : listData) {
    		domesticPaper.setAuditor("~");//设置修改人用户编码
    		domesticPaper.setAuditortime("~");//设置修改时间
		}
    	try {
    		this.domesticPaperService.verify(listData,false);
		} catch (Exception e) {
			JSONObject jsono=new JSONObject();
			jsono.put("success", "error");
			jsono.put("message", "取消审核失败：原因是"+e.getMessage());
			return jsono;
		}
        return super.buildSuccess();
    }
    
    @RequestMapping(value = "/toExportExcel", method = {RequestMethod.POST})
    @ResponseBody
    public Object toExportExcel(@RequestBody String json,PageRequest pageRequest, SearchParams searchParams) {
        Page<DomesticPaper> page = this.domesticPaperService.selectAllByPage(pageRequest, searchParams);
        JSONObject parseObject = new JSONObject().parseObject(json);//要打印输出的数据
        
        return null;
//    	Map<String, Object> map = new HashMap<String, Object>();
//    	ArrayList<Object> arrayList = new ArrayList<Object>();
//        map.put("content", "");
//        arrayList.add(map);
//        return this.buildSuccess("data", map);
    	
    }

    @RequestMapping(value = "/toUploadPictures", method = {RequestMethod.POST})
    @ResponseBody
    public Object getUrls(@RequestBody String json, HttpServletRequest request, HttpServletResponse response) {
    	
    	JSONObject parseObject = JSONObject.parseObject(json);
    	List<String> urls = new ArrayList<String>();
    	List<PoundPictrueUrlEntity> entitys = new ArrayList<PoundPictrueUrlEntity>();
    	JSONObject jsono=new JSONObject();
    	if(parseObject.get("imgUrl") == null){
    		jsono.put("success", "error");
    		jsono.put("message", "上传失败，没有得到图片路径");
    		return jsono;
    	}
    	
    	// 图片路径
    	urls = (List<String>) parseObject.get("imgUrl");
    	// 磅单主键
    	String pk_pound = parseObject.get("pk_pound").toString();
    	if(urls == null || urls.size() == 0){
    		jsono.put("success", "error");
    		jsono.put("message", "上传失败，没有得到图片路径");
    		return jsono;
    	}
    	for (String url : urls) {
    		PoundPictrueUrlEntity entity = new PoundPictrueUrlEntity();
    		url = url.replace("http://164.70.12.52:9090", "https://jxerp.zjjxjt.com:16431");
    		entity.setUrl(url);
    		entity.setBillid(pk_pound);
    		entity.setId(""+System.nanoTime());
    		entitys.add(entity);
    		try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
			}
		}
		// 执行插入
		this.domesticPaperService.savePictureUrl(entitys); 
    	
        return super.buildSuccess();
    	
    }
}	